import aiohttp
import logging
import os

class GitHubProxySession(aiohttp.ClientSession):

    PROXY_PREFIX = os.getenv("GITHUB_PROXY", "https://jiashu.1win.eu.org/")
    ENABLED = True

    def _prepare_url(self, url):
        if not self.ENABLED:
            return url
            
        if isinstance(url, str) and url.startswith(("https://raw.githubusercontent.com/", "https://github.com/")):
            logging.info(f"Using GitHub proxy: {self.PROXY_PREFIX + url}")
            return self.PROXY_PREFIX + url
        return url

    async def _request(self, method, url, **kwargs):
        try:
            url = self._prepare_url(url)
            return await super()._request(method, url, **kwargs)
        except aiohttp.ClientError as e:
            if self.PROXY_PREFIX in url:  # 代理失败时尝试直连
                logging.warning(f"Proxy failed, retrying direct: {e}")
                original_url = url.replace(self.PROXY_PREFIX, "", 1)
                return await super()._request(method, original_url, **kwargs)
            raise

# 全局替换 aiohttp.ClientSession
aiohttp.ClientSession = GitHubProxySession

logging.info(f"INIT GitHub proxy")
